package top.dreamix.abc


class MultiStepTaskRunner(
    private val steps: List<Step>,
    private val cache: TaskCache // 用于记录已完成步骤
) {

    suspend fun run(): Result {
        val completedSteps = mutableListOf<Step>()

        // 1. 跳过已缓存成功的步骤
        val startIndex = steps.indexOfFirst { !cache.isStepCompleted(it.name) }
        if (startIndex == -1) {
            // 所有步骤已完成
            return Result.Success
        }

        // 2. 从 startIndex 开始顺序执行
        for (i in startIndex until steps.size) {
            val step = steps[i]

            val result = step.execute()
            if (result is Result.Success) {
                cache.markStepCompleted(step.name)
                completedSteps.add(step)
            } else {
                // 3. 执行失败 → 逆序回滚已成功步骤
                rollback(completedSteps)
                return result // 返回第一个错误
            }
        }

        return Result.Success
    }

    private suspend fun rollback(stepsToRollback: List<Step>) {
        // 从后往前回滚（LIFO）
        for (step in stepsToRollback.asReversed()) {
            step.rollback() // 可选择忽略回滚失败，或记录日志
        }
        // 清除缓存中这些步骤的状态（可选）
        stepsToRollback.forEach { cache.clearStep(it.name) }
    }
}

interface TaskCache {
    fun isStepCompleted(stepName: String): Boolean
    fun markStepCompleted(stepName: String)
    fun clearStep(stepName: String)
}

interface Step {
    suspend fun execute(): Result
    suspend fun rollback(): Result // 回退操作，如删除临时文件、恢复旧配置等
    val name: String
}

// 辅助类型
sealed class Result {
    object Success : Result()
    data class Failure(val error: Throwable) : Result()
}

